package cn.itzzx.lagou.controller;

import cn.itzzx.lagou.pojo.LagouToken;
import cn.itzzx.lagou.service.CodeFeignClientService;
import cn.itzzx.lagou.service.LagouTokenService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * TODO
 *
 * @author Martin
 * @since 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private LagouTokenService lagouTokenService;

    @Resource
    private CodeFeignClientService codeFeignClientService;


    @PostMapping("register/{email}/{password}/{code}")
    public boolean register(@PathVariable("email") String email, @PathVariable("password") String password,@PathVariable("code") String code){
        if(codeFeignClientService.validate(email,code) == 0){
            return lagouTokenService.register(email,password,code);
        }else{
            return false;
        }
    }

    @PostMapping("isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email){
        boolean result = lagouTokenService.isRegistered(email);
        return result;
    }

    @PostMapping("login/{email}/{password}")
    public String login(HttpServletResponse response, @PathVariable("email") String email, @PathVariable("password") String password){
        LagouToken result = lagouTokenService.login(email, password);
        if (result == null){
            return "";
        }else {
            Cookie cookie = new Cookie("token", result.getToken());
            response.addCookie(cookie);
            return result.getEmail();
        }
    }

    @PostMapping("info/{token}")
    public String info(@PathVariable("token")String token){
        String email = lagouTokenService.info(token);
        return email;
    }
}
